/**
 * @author ens12ilt - ens12ple
 */

package parser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import model.Image;

public final class ImageParser {

	private static final int COL_SIZE = 20;
	private static final String REGEX_IMAGE_NAME_LINE = "^Image[0-9]+";
	private static final String REGEX_IMAGE_LINE = "^([0-9]+ +){"+ (COL_SIZE - 1) +"}[0-9]+";
	
	/**
	 * 
	 * @param fileName name of the file containing the image
	 * @return the images
	 * @throws IOException
	 */
	public static ArrayList<Image> parseFile(String fileName) throws IOException{
		ArrayList<Image> images = new ArrayList<Image>();
		FileReader in = new FileReader(fileName);
		BufferedReader buffer = new BufferedReader(in);
		String line;
		while((line = buffer.readLine()) != null){
			if(line.matches(REGEX_IMAGE_NAME_LINE)){
				Image img = new Image(line);
				int i = 0;
				int[] pixelLineValues = new int[COL_SIZE];
				while((line = buffer.readLine()).matches(REGEX_IMAGE_LINE)){
					String[] pixelValues = line.split(" ");
					for(int j = 0; j < COL_SIZE; j++){
						pixelLineValues[j] = Integer.parseInt(pixelValues[j]);
					}
					img.setImageRow(i, pixelLineValues);
					i++;
				}
				images.add(img);
			}			
		}
		return images;
	}
	
}
